<template>
	<el-container>
		<!--  v-if="orgType==2" -->
		<el-header>
			<div class="left-panel"> </div>
			<div class="right-panel">
				<el-button :icon="Search"   type="primary" @click="opBindData">查询</el-button>
				<el-button :icon="Search" type="info" plain @click="resetSearch">重置</el-button>
				<el-button text type="primary" @click="showCondition = !showCondition">
					<span v-if="!showCondition">展开</span>
					<span v-else>收起</span>
					<vab-icon class="vab-dropdown" :class="{ 'vab-dropdown-active': fold }" icon="arrow-up-s-line" />
				</el-button>
			</div>
		</el-header>
		<el-foot v-show="showCondition">
			<vab-query-form-top-panel>
				<el-form inline label-width="49px" :model="queryForm" style="margin-top: 5px">
					<el-form-item label="对账时间" label-width="100px">
						<el-date-picker style="width: 300px" v-model="queryList.accountDate" type="datetimerange"
							value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss" range-separator="-"
							unlink-panels="true" start-placeholder="开始时间" end-placeholder="结束时间" :default-time="defaultTime"/>
					</el-form-item>
					<el-form-item label="对账申请编号" label-width="100px">
						<el-input placeholder="---请输入对账申请编号---" v-model="queryList.accountCode" style="width: 300px" />
					</el-form-item>
					<el-form-item label="对账申请日期" label-width="100px">
						<el-date-picker style="width: 300px" v-model="queryList.accountTime" type="datetimerange"
							value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss" range-separator="-"
							unlink-panels="true" start-placeholder="开始时间" end-placeholder="结束时间" :default-time="defaultTime"/>
						<!-- <el-input placeholder="---请输入对账申请日期---" v-model="queryList.accountTime" style="width: 300px" /> -->
					</el-form-item>
					<el-form-item label="申请人" label-width="100px">
						<el-input placeholder="---请输入申请人---" v-model="queryList.applicantUser" style="width: 300px" />
					</el-form-item>
					<el-form-item label="联系电话" label-width="100px">
						<el-input placeholder="---请输入联系电话---" v-model="queryList.tel" style="width: 300px" />
					</el-form-item>
					<el-form-item label="对账状态" label-width="100px">
						<el-select placeholder="---请选择状态---" v-model="queryList.reconciliationStatus"
							style="width: 300px">
							<el-option label="---请选择状态---" value />
							<el-option v-for="item in optionsState" :key="item.value" :label="item.label"
								:value="item.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="客户" label-width="100px">
						<el-input placeholder="---请输入客户名称---" v-model="queryList.storeName" style="width: 300px" />
					</el-form-item>
					<el-form-item label="物料简码" label-width="100px">
						<el-input placeholder="---请输入物料简码---" v-model="queryList.materialSimpCode"
							style="width: 300px" />
					</el-form-item>
					<el-form-item label="物料编号" label-width="100px">
						<el-input placeholder="---请输入物料编号---" v-model="queryList.materialCode" style="width: 300px" />
					</el-form-item>
					<el-form-item label="物料分类" label-width="100px">
						<el-tree-select v-model="queryList.materialTypeIds"
						placeholder="---请选择物料分类---"
							:props="{ label: 'label', value:'value',children: 'children' }" :data="materialTypeTree"
							multiple :render-after-expand="false" show-checkbox style="width: 300px" />
					</el-form-item>
					<el-form-item label="物料名称" label-width="100px">
						<el-input placeholder="---请输入物料名称---" v-model="queryList.materialName" style="width: 300px" />
					</el-form-item>
					<el-form-item label="规格型号" label-width="100px">
						<el-input placeholder="---请输入规格型号---" v-model="queryList.materialSpecs" style="width: 300px" />
					</el-form-item>
				</el-form>
			</vab-query-form-top-panel>
		</el-foot>

		<el-main class="nopadding">
			<scTable ref="mytable" border :queryType="'sales-account/pages'"
				:data="listData" :queryList="queryList" :column="columnList" :orderList="OrderList"
				:sort-orders="['ascending', 'descending']" @selection-change="selectionChange"
				row-key="ReceivingOrderId" key="ReceivingOrderId"  :row-class-name="setRowClass" show-summary remoteSummary>
				<el-table-column label="序号" type="index" width="80" align="center"></el-table-column>
				<el-table-column label="对账申请编号" prop="accountCode" width="160" sortable>
					 <template #default="scope"> <span class="el-span-text" @click="opHandleView(scope.row, scope.$index)">{{scope.row.accountCode}}</span></template>
				</el-table-column>
				<el-table-column label="对账申请日期" prop="accountTime"  min-width="200" sortable></el-table-column>
				<el-table-column label="对账日期" width="200" sortable>
					<template #default="scope">
						{{scope.row.accountStartDate.length>10? scope.row.accountStartDate.slice(0, 10):scope.row.accountStartDate}}
						{{'-'}}
						{{scope.row.accountEndDate.length>10? scope.row.accountEndDate.slice(0, 10):scope.row.accountEndDate}}
					</template>
				</el-table-column>
				<el-table-column label="对账申请单位" prop="purchaseUnityFullName" width="250" sortable>
					<!-- <template #default="">
						{{'酒业贸易'}}
					</template> -->
				</el-table-column>
				<el-table-column label="申请人" prop="applicantUser"  min-width="110" sortable></el-table-column>
				<el-table-column label="联系电话" prop="tel" min-width="110" sortable></el-table-column>
				<el-table-column label="客户" prop="storeName" min-width="140" sortable></el-table-column>
				<el-table-column label="对账明细表" prop="materialCode" width="120">
					<template #default="scope">
						<el-button-group>
							<el-button text type="primary" size="small" @click="opHandleView(scope.row, '3')">查看</el-button>
							<el-button text type="primary" size="small" @click="opExport(scope.row)">下载</el-button>
						</el-button-group>
					</template>
				</el-table-column>
				<el-table-column label="相关附件" prop="materialName" width="120">
					<template #default="scope">
						<el-button-group>
							<el-button v-if="scope.row.accountFile!=''" text type="primary" size="small" @click="opOfficePreview(scope.row, scope.$index)">查看</el-button>
							<el-button text type="primary" size="small" @click="opDownFile(scope.row, scope.$index)">下载</el-button>
						</el-button-group>
					</template>
				</el-table-column>
				<el-table-column label="对账状态" prop="storeReconciliationStatus" min-width="100">
					<template #default="scope">
						{{scope.row.storeReconciliationStatus==0?'已关账':''}}
						{{scope.row.storeReconciliationStatus==1?'已对账':''}}
						{{scope.row.storeReconciliationStatus==2?'已发送申请':''}}
						{{scope.row.storeReconciliationStatus==3?'对账中':''}}

					</template>
				</el-table-column>
				<el-table-column label="操作" fixed="right" width="150" align="center">
					<template #default="scope">
						<el-button-group>
							<!-- <el-button v-if="scope.row.storeReconciliationStatus==2" text type="primary" size="small" @click="opStartAccount(scope.row, scope.$index)">开始对账</el-button> -->
							<el-button v-if="scope.row.storeReconciliationStatus==3||scope.row.storeReconciliationStatus==2" text type="primary" size="small" @click="opShow(scope.row, scope.$index)">进行对账</el-button>
						</el-button-group>
					</template>
				</el-table-column>
			</scTable>

		</el-main>
	</el-container>
	<reconciliation-doing v-if="dialogCheck" ref="checkDialog" @fatherMethod="opBindData" @success="handleSaveSuccess" @closed="closed"></reconciliation-doing>

	<!-- 预览文件 -->
	<officeViewer  ref="officeDialog" />
</template>

<script>
	import publicjs from "@/api/model/publicjs";
	import tool from "@/utils/tool";
	import reconciliationDoing from "./reconciliationDoing"
	export default {
		components: {
			publicjs,
			reconciliationDoing,
		},
		data() {
			return {
				orgType: '',
				columnList: [],
				queryList: {},
				selectionRows: [],
				showCondition: false,
				dialogCheck: false,
				materialTypeTree: [],
				optionsState: [{
						value: 1,
						label: '已对账'
					},
					{
						value: 2,
						label: '未对账'
					},
					{
						value: 3,
						label: '对账中'
					},
					{
						value: 4,
						label: '已发送申请'
					}
				],
				defaultTime:[
					new Date(2000, 1, 1, 0, 0, 0),
					new Date(2000, 2, 1, 23, 59, 59),
				]
			}
		},
		methods: {
			opOfficePreview(row){
				// 预览操作，打开对话框显示图片
				this.$refs.officeDialog.setData(row.accountFile);
				this.$refs.officeDialog.open();
			},
			opHandleView(row) {
				this.dialogCheck = true;
				this.$nextTick(() => {
					this.$refs.checkDialog.initTable(row, '3');
				});
			},
			// 编辑申请 type = 2
			opPrintview(row) {
				this.dialogCheck = true;
				this.$nextTick(() => {
					this.$refs.checkDialog.initTable(row, '2');
				});
			},
			//进行对账 type = 1
			opShow(row) {
				this.dialogCheck = true;

				this.opStartAccount(row);
				this.$nextTick(() => {
					this.$refs.checkDialog.initTable(row, '1');
				});
			},
			async opBindData() {
				this.$refs.mytable.clearSort();
				this.$refs.mytable.getData();
			},
			resetSearch() {
				this.queryList = {}
			},
			setRowClass({ row }) {
            if (this.selectionRows.includes(row)) {
                return "selected-row-color";
            }
            return "";
    },
			//表格选择后回调事件
			selectionChange(selection) {
				this.selectionRows = selection;
				console.log(this.selectionRows)
			},
			async opExport(row) {
				try {
					var response = await this.$API.auth.PostDownApi.post(
						"sales-account/export", {
							salesAccountID: row.salesAccountID,
							accountStartDate: row.accountStartDate,
							accountEndDate: row.accountEndDate
						}
					);
					var beginDate=row.accountStartDate.substring(0,10);
					var endDate=row.accountEndDate.substring(0,10)

					// 获取 Content-Disposition 头部信息
					// debugger;
					const headers = new Headers(response.headers);
					console.log("headers",headers);
					let fileName = headers.get("File-Name");
					console.log("fileName",fileName);
					fileName = decodeURIComponent(fileName);
					
					if (!fileName || fileName == "null") {
						fileName = "对账明细("+beginDate+"至"+endDate+").xlsx";
					}
					console.log(fileName);
					const blob = new Blob([response.data], {
						type: "application/xlsx",
					});
					// 创建一个临时的 URL 对象，指向下载的 Blob 数据
					const url = window.URL.createObjectURL(blob);
					// 创建一个 <a> 元素，设置其 href 属性为 URL，并触发点击
					const a = document.createElement("a");
					a.href = url;
					a.download = fileName; // 下载时显示的文件名为从头信息中获取的文件名
					document.body.appendChild(a); // 将 <a> 元素添加到 DOM 中
					a.click(); // 模拟点击下载
					document.body.removeChild(a); // 下载完成后移除 <a> 元素
					window.URL.revokeObjectURL(url); // 释放 Blob 对象
				} catch (error) {
					this.loading = false;
					this.$message.error(error.message);
					// this.$alert(error.message, "提示", {
					// 	type: "error"
					// });
					return false;
				}
			},
			opDownFile(row) {
				// debugger
				if (row.accountFile == null || row.accountFile.length <= 0) {
					this.$message.error('暂无附件');
				} else {
					const url = new URL(row.accountFile);
					const fileName = url.pathname.split('/').pop(); // 获取文件名
					fetch(row.accountFile)
						.then(response => response.blob())
						.then(blob => {
							const url = URL.createObjectURL(blob);
							const a = document.createElement('a');
							a.style.display = 'none';
							a.href = url;
							a.download = fileName;
							document.body.appendChild(a);
							a.click();
							window.URL.revokeObjectURL(url);
						})
						.catch(error => console.error('下载失败:', error));
				}
			},
			//开始对账
			async opStartAccount(row) {
				try {
					var response = await this.$API.auth.PostDownApi.post(
						"sales-account/startaccount", {
							salesAccountID: row.salesAccountID
						}
					);
					if (response.status == 200) {
						this.opBindData()
					} else {
						this.$message.error("操作失败:" + response.msg);
					}
				} catch (error) {
					this.loading = false;
					this.$message.error(error.message);
					return false;
				}
			},
			async initOptions() {
				try {
					var returnValue = await this.$API.auth.PostProcessApi.post(
						"material-type/tree", {
							status: 1
						}
					);
					if (returnValue.status == 200) {
						this.materialTypeTree = returnValue.response;
					} else {
						this.$message.error("操作失败:" + returnValue.msg);
					}
				} catch (error) {
					this.loading = false;
					return false;
				}
			},
			closed() {
				this.dialogCheck = false
				this.$nextTick(() => {
					this.$refs.mytable.reload()
				})
			},
			handleSaveSuccess(){
				this.$nextTick(() => {
					this.$refs.mytable.reload()
					// this.$refs.mytable.clearSort();
				    // this.$refs.mytable.getData();
				})
			}
		},
		async mounted() {
			this.orgType = tool.data.get("USER_INFO").AccountType;
			await this.opBindData();
			await this.initOptions();
		},
	}
</script>

<style lang="scss" scoped>
/* 当表格行处于悬停状态时改变背景颜色 */
::v-deep .el-table .el-table__row:hover {
    background-color: #dae8f7;
}
::v-deep .el-table__body .el-table__row--striped.hover-row td {
    background-color: #dae8f7 !important;
}
//   斑马纹选中颜色
::v-deep .el-table__body .el-table__row--striped.selected-row-color td {
    background-color: #b8dcff !important;
}
::v-deep .el-table {
    --el-table-row-hover-bg-color: #dae8f7;
}

::v-deep .el-table tr:nth-child(2n) {
    background: #f2f2f2;
}
</style>
<style>
.el-table .selected-row-color {
    background-color: #b8dcff !important;
}
.el-table--enable-row-hover .el-table__body tr.selected-row-color:hover > td {
    background-color: #b8dcff !important;
}
.el-table__body-wrapper .el-table__body tr.selected-row-color.hover-row > td {
    background-color: #b8dcff !important;
}
.el-table__fixed-body-wrapper
    .el-table__body
    tr.selected-row-color.hover-row
    > td {
    background-color: #b8dcff !important;
}
.el-table__body-wrapper
    .el-table__body
    tr.selected-row-color.hover-row
    > .el-table__row--striped {
    background-color: #b8dcff !important;
}
</style>




